package cn.xxi.ai.workflow.core.node.start;

import cn.xxi.ai.workflow.core.node.NormalNode;
import cn.xxi.ai.workflow.core.node.Position;
import cn.xxi.ai.workflow.core.node.Style;
import cn.xxi.ai.workflow.state.State;
import lombok.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 表示流程的起始节点
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Builder
public class StartNode extends NormalNode<StartData> {

    private String id;
    private StartData data;
    private Position position;
    private Style style;

    @Override
    public String getId() {
        return id;
    }

    @Override
    public StartData getData() {
        return data;
    }

    @Override
    public Position getPosition() {
        return position;
    }

    @Override
    public Style getStyle() {
        return style;
    }

    /**
     * 处理起始节点的变量检查与输出。
     *
     * 如果存在必填变量未在 state 中定义，则抛出异常。
     * 否则将变量以 "节点ID.变量名" 为 key 输出。
     */
    @Override
    public Map<String, Object> process(State state) throws IllegalAccessException {
        List<String> missingVariables = data.getVariables().stream()
                .filter(StartData.Variable::isRequired)
                .map(StartData.Variable::getVariable)
                .filter(var -> state.any(var) == null)
                .collect(Collectors.toList());

        if (!missingVariables.isEmpty()) {
            String msg = "missing required variable [" + String.join(", ", missingVariables) + "]";
            throw new IllegalAccessException(msg);
        }

        return data.getVariables().stream()
                .collect(Collectors.toMap(
                        v -> id + "." + v.getVariable(),
                        v -> state.any(v.getVariable()) // Kotlin 使用 !!，Java 需要保证非 null 或信任状态管理器
                ));
    }
}
